//
//  YHRefresh.swift
//  YHRefresh
//
//  Created by yuhao.mac on 16/7/2.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit
//刷新控件的状态枚举
enum YHRefreshType: Int{
    //正常
    case Normal = 0
    //下拉
    case Pulling = 1
    //刷新中
    case Refreshing = 2
}

let YHRefreshHeight: CGFloat = 50

class YHRefresh: UIControl {
    
    //被观察者
    var scrollView: UIScrollView?
    
    var refreshState:YHRefreshType = .Normal{
        didSet{
            switch refreshState{
            case .Normal:
                messageLabel.text = "正常"
                // 如果我们上一个状态为刷新中才开始动画
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= YHRefreshHeight
                    })
                }
                
            case .Pulling:
                messageLabel.text = "下拉中"
            case .Refreshing:
                messageLabel.text = "刷新中"
                // 动画设置contentInset.top
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += YHRefreshHeight
                    }, completion: { (_) -> Void in
                        // 相似发送通知
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }
    

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -YHRefreshHeight, width: SCREENW, height: YHRefreshHeight))
        setupUI()
    }
    
    func endRefreshing(){
        refreshState = .Normal
    }
    
    func setupUI(){
    
        backgroundColor = UIColor.orangeColor()
        addSubview(messageLabel)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        messageLabel.frame = CGRect(x: 0, y: 0, width: SCREENW, height: YHRefreshHeight)
    }
    
    //KVO的使用
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        
        self.scrollView = scrollView
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    //观察者中实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let contentoffSetY = self.scrollView!.contentOffset.y
        let contentInsetTop = self.scrollView!.contentInset.top
        
        if scrollView!.dragging{
            if contentoffSetY > -contentInsetTop - YHRefreshHeight  && refreshState == .Pulling{
                
                refreshState = .Normal
            }else if contentoffSetY <=  -contentInsetTop - YHRefreshHeight && refreshState == .Normal {
                refreshState = .Pulling
            }
            
        }else {
            // 用户松手
            if refreshState == .Pulling{
                refreshState = .Refreshing
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFontOfSize(15)
        lab.textColor = UIColor.whiteColor()
        lab.textAlignment = .Center
        lab.text = "正常"
        return lab
    }()
    
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
